<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/20
 * Time: 20:10
 */

namespace App\Handler;

use Illuminate\Support\Facades\Log;
use OSS\OssClient;
use OSS\Core\OssException;

trait ImageHandler
{

	/**
	 *  图片处理类
	 * User: ihome
	 * @param string $folder_path 上传的文件夹
	 * @param string $form_name 表单名
	 * @param string $file_prefix 文件名前缀
	 * @param string $size 文件大小 默认是5MB
	 * @return array
	 */
	public function imageUploader($folder_path, $form_name, $file_prefix = '')
	{
		$file = request()->file($form_name);

		if ( ! file_exists($folder_path)) {
			mkdir($folder_path, 0777, true);
		}

		if ($file->isValid()) {
			//组合真正的物理上传路径
			$upload_path = public_path() . '/' . $folder_path . '/' . date('Ymd', time());

			//文件名后缀
			$ext = $file->getClientOriginalExtension();

			//允许的类型
			$allow_type = ['jpg', 'jpeg', 'png', 'gif'];

			if ( ! in_array($ext, $allow_type)) {
				return [
					'status' => '415',
					'msg'    => '上传文件类型错误',
				];
			}

			//判断文件是否超出大小
			$file_size = $file->getSize();

			//配置中的上传文件大小
			$size = \App\Models\WebConfig::find(9)->toArray();
			$size = $size['value'] * 1024 * 1024;
			if ($file_size > $size) {
				return [
					'status' => '415',
					'msg'    => '上传文件超出大小',
				];
			}

			//组合的文件名
			$file_name = $file_prefix . time() . uniqid() . '.' . $ext;
			//组合的上传路径
			$save_path = $folder_path . '/' . date('Ymd', time()) . '/' . $file_name;

			$file->move($upload_path, $file_name);

			return [
				'status' => 200,
				'path'   => $save_path,
			];
		}
	}


	/**
	 * 批量上传文件
	 * User: Clannad ~ ☆
	 * DataTime：2019/11/18 0018 11:38
	 * @param $folder_path
	 * @param $form_name
	 * @param string $file_prefix
	 * @return array
	 */
	public function batchImageUploader($folder_path, $form_name, $file_prefix = '')
	{
		$file = request()->file($form_name);

		if ( ! file_exists($folder_path)) {
			mkdir($folder_path, 0777, true);
		}

		$imgArr = [];

		foreach ($file as $k => $v) {
			if ($v->isValid()) {
				//组合真正的物理上传路径
				$upload_path = public_path() . '/' . $folder_path . '/' . date('Ymd', time());

				//文件名后缀
				$ext = $v->getClientOriginalExtension();

				//允许的类型
				$allow_type = ['jpg', 'jpeg', 'png', 'gif'];

				if ( ! in_array($ext, $allow_type)) {
					return [
						'status' => '415',
						'msg'    => '上传文件类型错误',
					];
				}

				//判断文件是否超出大小
				$file_size = $v->getSize();

				//配置中的上传文件大小
				$size = \App\Models\WebConfig::find(9)->toArray();
				$size = $size['value'] * 1024 * 1024;
				if ($file_size > $size) {
					return [
						'status' => '415',
						'msg'    => '上传文件超出大小',
					];
				}

				//组合的文件名
				$file_name = $file_prefix . time() . uniqid() . '.' . $ext;
				//组合的上传路径
				$save_path = $folder_path . '/' . date('Ymd', time()) . '/' . $file_name;

				$v->move($upload_path, $file_name);

				$imgArr[] = $save_path;//最终路径，加文件名
			}
		}

		return [
			'status' => 200,
			'imgs'   => $imgArr,
		];

	}

	/**
	 * 上传到阿里云OSS
	 * User: Clannad ~ ☆
	 * @param string $form_name 表单名
	 * @param string $prefix 文件名前缀
	 * @return array
	 */
	public function upLoadToAliOss($form_name, $folder_name = '', $prefix = '')
	{
		$accessKeyId     = config('alioss.accessKeyId');
		$accessKeySecret = config('alioss.accessKeySecret');
		$endpoint        = config('alioss.endpoint');
		$bucket          = config('alioss.bucket');

		$file = request()->file($form_name);

		if ($file->isValid()) {

			//文件名后缀
			$ext = $file->getClientOriginalExtension();

			//允许的类型
			$allow_type = ['jpg', 'jpeg', 'png', 'gif'];

			if ( ! in_array($ext, $allow_type)) {
				return [
					'status' => '415',
					'msg'    => '上传文件类型错误',
				];
			}

			//判断文件是否超出大小
			$file_size = $file->getSize();

			//配置中的上传文件大小
			$size = \App\Models\WebConfig::find(9)->toArray();
			$size = $size['value'] * 1024 * 1024;
			if ($file_size > $size) {
				return [
					'status' => '415',
					'msg'    => '上传文件超出大小',
				];
			}

			//先上传到本地临时文件
			$upload_path = public_path() . '/uploads/tmp_path/';
			$file_name   = $prefix . time() . uniqid() . '.' . $ext;
			$file->move($upload_path, $file_name);
			//开始处理阿里云上传逻辑
			try {
				$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
				$result    = $ossClient->uploadFile($bucket, $folder_name . $file_name, $upload_path . $file_name);

				if ($result['info']['http_code'] == 200) {
					//删除源文件
					unlink($upload_path . $file_name);

					return [
						'status' => '200',
						'path'   => $result['info']['url'],
					];
				}

			} catch (OssException $e) {

				Log::info('【OSS上传失败】原因：' . $e->getMessage());

				return [
					'status' => '415',
					'msg'    => '图片上传失败，请联系管理员',
				];
			}
		}
	}

	/**
	 * 删除阿里云OSS文件
	 * User: Clannad ~ ☆
	 * @param $file_name string 文件名
	 */
	public function delAliOssFile($file_name, $folder_name = '')
	{
		$accessKeyId     = config('alioss.accessKeyId');
		$accessKeySecret = config('alioss.accessKeySecret');
		$endpoint        = config('alioss.endpoint');
		$bucket          = config('alioss.bucket');

		try {
			$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$ossClient->deleteObject($bucket, $folder_name . $file_name);
		} catch (OssException $e) {
			Log::info('【OSS上传失败】原因：' . $e->getMessage() . '文件名：' . $folder_name . $file_name);
		}
	}

	/**
	 * 截取文件名
	 * User: Clannad ~ ☆
	 * DataTime：2020/3/22 0022 10:24
	 * @param $file_url
	 */
	public function cutFileName($file_url)
	{
		return str_replace('http://myclannad.oss-cn-shenzhen.aliyuncs.com/', '', $file_url);
//		return substr($file_url,$index + 1);
	}


	/**
	 * 批量上传文件到阿里云
	 * User: Clannad ~ ☆
	 */
	public function batchUploadToAliOss($form_name, $folder_name = '', $file_prefix = '')
	{
		$accessKeyId     = config('alioss.accessKeyId');
		$accessKeySecret = config('alioss.accessKeySecret');
		$endpoint        = config('alioss.endpoint');
		$bucket          = config('alioss.bucket');

		$file = request()->file($form_name);

		$imgArr = [];

		$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

		foreach ($file as $k => $v) {
			if ($v->isValid()) {
				//组合真正的物理上传路径
				$upload_path = public_path() . '/uploads/tmp_path/';

				//文件名后缀
				$ext = $v->getClientOriginalExtension();

				//允许的类型
				$allow_type = ['jpg', 'jpeg', 'png', 'gif'];

				if ( ! in_array($ext, $allow_type)) {
					return [
						'status' => '415',
						'msg'    => '上传文件类型错误',
					];
				}

				//判断文件是否超出大小
				$file_size = $v->getSize();

				//配置中的上传文件大小
				$size = \App\Models\WebConfig::find(9)->toArray();
				$size = $size['value'] * 1024 * 1024;
				if ($file_size > $size) {
					return [
						'status' => '415',
						'msg'    => '上传文件超出大小',
					];
				}

				//组合的文件名
				$file_name = $file_prefix . time() . uniqid() . '.' . $ext;
				$v->move($upload_path, $file_name);

				//开始处理阿里云上传逻辑
				try {

					/**
					 * 1.buckets
					 * 2.上传的文件位置，包括文件夹名称
					 * 3.本地文件名称
					 */
					$result = $ossClient->uploadFile($bucket, $folder_name . $file_name, $upload_path . $file_name);

					if ($result['info']['http_code'] == 200) {
						//删除源文件
						unlink($upload_path . $file_name);

						$imgArr[] = $result['info']['url'];
					}

				} catch (OssException $e) {

					Log::info('【OSS上传失败】原因：' . $e->getMessage());

					return [
						'status' => '415',
						'msg'    => '图片上传失败，请联系管理员',
					];
				}
			}
		}

		return [
			'status' => 200,
			'imgs'   => $imgArr,
		];

	}
}